#include "songtagger.h"

//#include<taglib/include/taglib/taglib.h>
//#include<taglib/include/taglib/fileref.h>
#include<C:/Program Files (x86)/taglib/include/taglib/taglib.h>
#include<C:/Program Files (x86)/taglib/include/taglib/fileref.h>
#include<QStringList>

SongTagger::SongTagger()
{

}

SongTagger::~SongTagger()
{

}

void guessTag(const QUrl &url, SongData *data){
    //printf("\tfailed, will guess now...\n");
    QString s = url.fileName();
    QStringList strl = s.split(".", QString::SkipEmptyParts);

    //String part before last . (file suffix) should be title.
    data->title = strl[strl.size()-2].trimmed();
    //printf("Guessed title %s\n", data->title.toUtf8().data());

    //Removing artist/album names etc
    if(data->title.contains('-')){
        //printf("\ttitle contains '-'\n");
        strl = data->title.split('-', QString::SkipEmptyParts);
        if(strl.size() >= 3){
            //printf("CASE 3\n");
            data->artist = strl[0].trimmed();
            data->album = strl[1].trimmed();
            for(int i = 2; i < strl.size(); i++){
                if(i>2)
                    data->title.append("-");
                data->title.append(strl[i]);
            }
        }else if(strl.size() == 2){
            //printf("CASE 2\n");
            data->artist = strl[0].trimmed();
            data->title = strl[1].trimmed();
        }else if(strl.size() == 1){
            //printf("CASE 1\n");
            //Title should already be correct I think.
        }
    }

}

void SongTagger::readTag(const QUrl &url, SongData *data){
    //TagLib::FileRef f(url.toLocalFile().toUtf8().data());
    TagLib::FileRef f(url.toLocalFile().toLocal8Bit().data());
    //printf("SongTagger::readTag(%s)\n", url.toLocalFile().toLocal8Bit().data());
    if(f.isNull()){
        guessTag(url, data);
        return;
    }

    TagLib::Tag *tag = f.tag();

    if(tag == 0){
        guessTag(url, data);
        return;
    }

    data->title = tag->title().toCString(true);
    data->artist = tag->artist().toCString(true);
    data->album = tag->album().toCString(true);

    data->track = tag->track();
    if(f.audioProperties())
            data->duration = f.audioProperties()->length() * 1000;
}

void SongTagger::writeTag(const QUrl &/*url*/, SongData */*data*/){
//We'll do this later. It has limited purpose anyway.
}
